package com.hxx.day9.mysqldb;

import java.lang.reflect.Field;

public class BaseMapper {
    //保存:insert into table(fields) values (?)
   public void save(Person person){
       StringBuilder sb = new StringBuilder();
       sb.append("insert into ");
       //反射类型
       Class<?> clazz = person.getClass();
       //获取类上的注解
       Table table = clazz.getAnnotation(Table.class);
       if (table!=null){
           //获取表名
           sb.append(table.value());
       }else {
           //默认表名
           sb.append(clazz.getSimpleName().toLowerCase());
       }
       sb.append("(");
       //拼接字段
       //获取所有字段
       Field[] fields = clazz.getDeclaredFields();
       String zwf = "";
       for (Field field : fields) {
           zwf += "?,";
           //判断是否有注解
           if (field.isAnnotationPresent(Column.class)){
               //获取注解
               Column column = field.getAnnotation(Column.class);
               //获取字段名
               String fieldName = column.value();
               if (fieldName.isEmpty()){
                   //默认字段名
                   fieldName = field.getName();
               }
               sb.append(fieldName).append(",");
           }else {
               //默认字段名
               sb.append(field.getName()).append(",");
           }
       }
       //删除最后一个逗号
       sb.deleteCharAt(sb.length()-1);
       sb.append(") values (");
       //删除最后一个逗号
       zwf = zwf.substring(0,zwf.length()-1);
       sb.append(zwf).append(")");
       System.out.println(sb);
   }

    public static void main(String[] args) {
        Person person = new Person();
        person.setId(1001);
        person.setName("张三");
        person.setAge(18);
        BaseMapper baseMapper = new BaseMapper();
        baseMapper.save(person);
    }
}
























